package com.myblog.config.swagger;


import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.myblog.common.CommonConstant;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {
    private static final String VERSION = "v1.0.1";
    @Value("${swagger.enable}")
    private boolean enable;

    @Bean
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("接口文档").description("博客系统接口文档").version(VERSION).build();
    }


    @Bean
    public Docket appDocket() {
        return docket("^.*(?)/app/.*$", "app");
    }

    @Bean
    public Docket pcDocket() {
        return docket("^((?!/app/).)*$", "pc");
    }

    public Docket docket(String regex, String groupName) {
        List<ResponseMessage> responseMessageList = new ArrayList<>(1);
        responseMessageList.add(new ResponseMessageBuilder().code(CommonConstant.REQUEST_SUCCESS_CODE)
                .message(CommonConstant.REQUEST_SUCCESS_MESSAGE).responseModel(new ModelRef("R")).build());
        Parameter parameter = new ParameterBuilder().name(CommonConstant.TOKEN).description("登录凭证")
                .modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).enable(enable)
                .useDefaultResponseMessages(false)
                .groupName(groupName)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.PATCH, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .globalOperationParameters(Arrays.asList(parameter)).select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.regex(regex)).build();
    }
}
